<?php

class DefaultController extends MyAdminController
{
	public $modelName = 'Menu';
	
	public function actionIndex()
	{
		$model = new $this->modelName('search');

//		$id = is_null($id) ? $this->_getMinId() : $id;
		$this->render('index', array_merge(array('model'=>$model)));
	}
	
//	private function _getMinId()
//	{
//		$model = new $this->modelName;
//		$minId = Yii::app()->db->createCommand()
//			->select('MIN(id) as maxSorter')
//			->from($model->tableName())
//			->where('parent=0')
//			->queryScalar();
//		return $minId;
//	}
	
	public function actionCreate()
	{
		$model=new Menu();

		// Uncomment the following line if AJAX validation is needed
//		$this->performAjaxValidation($model);
		
		if(isset($_POST[$this->modelName]))
		{
			$model->attributes=$_POST[$this->modelName];
			if($model->save())
			{
				Yii::app()->user->setFlash('success', tt('Menu successfully created'));
				$this->redirect(array('index'));
			}
		}

		$this->render('create',array('model'=>$model));
	}
	
	public function actionUpdate($id)
	{
		if($this->_model === null){
			$model = $this->loadModel($id);
		}
		else{
			$model = $this->_model;
		}

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST[$this->modelName]))
		{
			$model->attributes=$_POST[$this->modelName];
			if($model->save())
				$this->redirect(array('index'));
		}

		$this->render('update',array('model'=>$model));
	}
	
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			Yii::app()->user->setFlash('success', tt('Menu successfully deleted'));
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	public function actionView($id, $parent=0)
	{
		$this->getMaxSorter($parent);
		$menu = $this->loadModel($id);
		$parentMenu = (!empty($parent)) ? Menu_items::model()->resetScope()->findByPk($parent) : false;
		
		$model = Menu_items::model();
		$this->params = array_merge($this->params, array(
			'model'=>$model, 'menu'=>$menu, 'parentMenu'=>$parentMenu, 'parent'=>$parent
		));
		$this->render('view',$this->params);
	}
	
	public function getMaxSorter($parent)
	{
		$model = new Menu_items();
		$maxSorter = Yii::app()->db->createCommand()
			->select('MAX(sorter) as maxSorter')
			->from($model->tableName())
			->where('parent='.$parent)
			->queryScalar();
		$this->params['maxSorter'] = $maxSorter;
	}
	
	public function actionMove(){
		if(isset($_GET['id']) && isset($_GET['direction'])){
			$direction = isset($_GET['direction']) ? $_GET['direction'] : '' ;

			$model = Menu_items::model()->resetScope()->findByPk($_GET['id']);

			if($model && ($direction == 'up' || $direction == 'down') ){
				$addWhere = ' AND parent="'.$model->parent.'"';
			    
				$sorter = $model->sorter;
				
				if($direction == 'up'){
					if($sorter > 1){
						$sql = 'UPDATE '.$model->tableName().' SET sorter="'.$sorter.'" WHERE sorter < "'.($sorter).'" '.$addWhere.' ORDER BY sorter DESC LIMIT 1';
						Yii::app()->db->createCommand($sql)->execute();
						$model->sorter--;
						$model->save();
					}
				}
				if($direction == 'down'){
					$maxSorter = Yii::app()->db->createCommand()
					->select('MAX(sorter) as maxSorter')
					->from($model->tableName())
					->queryScalar();
					
					if($sorter < $maxSorter){
						$sql = 'UPDATE '.$model->tableName().' SET sorter="'.$sorter.'" WHERE sorter > "'.($sorter).'" '.$addWhere.' ORDER BY sorter ASC LIMIT 1';
						Yii::app()->db->createCommand($sql)->execute();
						$model->sorter++;
						$model->save();
					}
				}
			}
		}
		if(!Yii::app()->request->isAjaxRequest){
			$this->redirect(isset($_GET['returnUrl']) ? $_GET['returnUrl'] : array('view', 'id'=>$model->menu_id, 'parent'=>$model->parent));
		}
	}

	public function actionCreateItem($id, $parent=0)
	{
		$menu = $this->loadModel($id);
		
		$model = new Menu_items();
		$model->setAttribute('parent', $parent);
		$model->setAttribute('menu_id', $id);
		// Uncomment the following line if AJAX validation is needed
//		$this->performAjaxValidation($model);
		
		if(isset($_POST[get_class($model)]))
		{
			$model->attributes=$_POST[get_class($model)];
			if($model->save())
			{
				Yii::app()->user->setFlash('success', tt('Menu item successfully created'));
				$this->redirect(array('view', 'id'=>$id));
			}
		}

		$this->render('create_item',array('model'=>$model, 'parent'=>$parent));
	}
	
	public function actionUpdateItem($id)
	{
		$model = Menu_items::model()->resetScope()->findByPk($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST[get_class($model)]))
		{
			$model->attributes=$_POST[get_class($model)];
			if($model->save())
				$this->redirect(array('view', 'id'=>$model->menu_id, 'parent'=>$model->parent));
		}

		$this->render('update_item',array('model'=>$model));
	}
	
	public function actionDeleteItem($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			
			Menu_items::model()->resetScope()->findByPk($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			Yii::app()->user->setFlash('success', tt('Menu successfully deleted'));
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
}